#include "PluginManager.h"
#include <dlfcn.h>
#include <iostream>

typedef RobotFactory* ( robotLoader)();
typedef ObstacleFactory* ( obstacleLoader)();

using namespace std;

void PluginManager::loadPlugin(const char* filename) {
	void* handle = dlopen(filename, RTLD_LAZY);
	if (!handle) {
		cerr << "Cannot open library: " << dlerror() << '\n';
		return;
	}
	robotLoader* loader = (robotLoader*) dlsym(handle, "createRobotFactory");
	if (!loader) {
		cerr << "Cannot load symbol: " << dlerror() << '\n';
		dlclose(handle);
		return;
	}
	robotFactory = loader();

	obstacleLoader* oloader = (obstacleLoader*) dlsym(handle,
			"createObstacleFactory");
	if (!oloader) {
		cerr << "Cannot load symbol: " << dlerror() << '\n';
		dlclose(handle);
		return;
	}
	obstacleFactory = oloader();
}

void PluginManager::registerRobotFactory(RobotFactory* factory) {
	robotFactory = factory;
}

RobotFactory* PluginManager::getRobotFactory() {
	return robotFactory;
}

ObstacleFactory* PluginManager::getObstacleFactory() {
	return obstacleFactory;
}

